package com.tulei.common.utils.file;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class ExcelHandler {

    /**
     * 读取Excel文件
     * @param filePath 文件路径
     * @param clazz 映射实体类
     */
    public <T> List<T> readExcel(String filePath, Class<T> clazz) {
        List<T> dataList = new ArrayList<>(); // 初始化数据容器
        try {
            EasyExcel.read(filePath, clazz, new DataListener<>(clazz, dataList)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("读取Excel时发生错误：" + e.getMessage());
        }
        return dataList; // 读取完成后返回数据列表
    }

    /**
     * 写入Excel文件
     * @param filePath 输出文件路径
     * @param data 要写入的数据列表
     */
    public <T> void writeExcel(String filePath, List<T> data) {
        // 设置样式策略
        WriteCellStyle headCellStyle = new WriteCellStyle();
        WriteCellStyle contentCellStyle = new WriteCellStyle();
        // 这里可以设置头、内容的样式
        HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headCellStyle, contentCellStyle);

        EasyExcel.write(filePath, data.get(0).getClass())
                .registerWriteHandler(styleStrategy)
                .sheet("数据信息")
                .doWrite(data);
    }

    public <T> File generateExcelToFile(List<T> data) throws IOException {
        // 设置样式策略
        WriteCellStyle headCellStyle = new WriteCellStyle();
        WriteCellStyle contentCellStyle = new WriteCellStyle();
        HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headCellStyle, contentCellStyle);

        // 创建临时文件
        File tempFile = File.createTempFile("temp_excel", ".xlsx");
        tempFile.deleteOnExit(); // 程序退出时自动删除

        try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
            EasyExcel.write(fileOutputStream, data.get(0).getClass())
                    .registerWriteHandler(styleStrategy)
                    .sheet("数据信息")
                    .doWrite(data);
        }

        return tempFile;
    }

    // 自定义监听器处理读取的数据
    private static class DataListener<T> extends AnalysisEventListener<T> {
        private final List<T> dataHolder;

        public DataListener(Class<T> clazz, List<T> dataHolder) {
            this.dataHolder = dataHolder;
        }

        @Override
        public void invoke(T data, AnalysisContext context) {
//            System.out.println("读取到一条数据: " + data);
            dataHolder.add(data);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            System.out.println("所有数据解析完成");
        }
    }
}